package com.xiaoyu.cloudmusic.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoyu.cloudmusic.resp.Payload;

import java.util.Base64;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static String SIGNATURE = "token!@#$%^7890";//加盐操作

    /**
     * 生成token
     * @param map //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR,7);//设置过期时间，JWT会在一周后过期
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();//JWT会被用HMAC-SHA256算法签署并转换为字符串
    }

    /**
     * 验证token
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static Payload getToken(String token) throws JsonProcessingException {
        DecodedJWT jwt=JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        String payload = jwt.getPayload();//获取到这个payload的base64字符串
        byte[] decodedBytes = Base64.getDecoder().decode(payload);//base64解码
        String decodedPayload = new String(decodedBytes);
        ObjectMapper mapper = new ObjectMapper(); // 创建ObjectMapper对象
        Payload payload1 = mapper.readValue(decodedPayload, Payload.class); // 将JSON字符串转换为Payload对象
        return payload1;
    }
}
